package com.erp.aopLog;

import cn.hutool.core.date.DateUtil;
import com.erp.Application;
import com.erp.entity.Adminlog;
import com.erp.enums.statusCode;
import com.erp.mapper.AdminlogMapper;
import com.erp.security.dto.JwtUserDto;
import com.erp.service.AdminlogService;
import eu.bitwalker.useragentutils.UserAgent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

public class Log {
    /**操作数据库 */
//    @Autowired
//    public AdminlogService adminlogService;
    /**
     * 自定义封装插入日志函数
     */
    public static void insert(String moduleName, String operation, Integer type){
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

        Adminlog adminLog = new Adminlog();
        //获取用户信息
        JwtUserDto jwtUserDto = (JwtUserDto) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if(jwtUserDto != null) {
            Integer userId = jwtUserDto.getMyUser().getUserId();
            String userName = jwtUserDto.getMyUser().getUserName();
            adminLog.setUserId(userId);
            adminLog.setUserName(userName);
        }
        // 获取浏览器信息
        UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("User-Agent"));
        adminLog.setBrowser(userAgent.getBrowser().getName());
        // 客户端ip
        adminLog.setLoginIp(request.getRemoteAddr());
        //操作类型
        adminLog.setType(type);
        // url
        String requestURL = request.getRequestURI();
        adminLog.setUrl(requestURL);
        //操作模块
        adminLog.setModuleName(moduleName);
        //操作内容
        adminLog.setOperation(operation);
        //创建时间
        adminLog.setCreatetime(DateUtil.now());
        //备注 TODO字段先预留

        //数据逻辑删除
        adminLog.setStatus(statusCode.Default.getValue());
        // 静态方法注入bean解决方案
        AdminlogService adminlogService = Application.ac.getBean(AdminlogService.class);
        adminlogService.save(adminLog);

    }
}
